import datetime
import os

from flask import Flask, request, render_template, jsonify

from dicom.dicom_convert import convert

app = Flask(__name__)
# 限制上传文件大小 16MB?
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024


@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'


@app.route('/dicom', methods=('GET', 'POST'))
def dicom():
    if request.method == 'GET':
        return render_template('dicom.html')
    dicom_file = request.files.get('dicom')
    if not dicom_file:
        return jsonify({
            'code': 400,
            'msg': 'dicom file not found'
        })
    # 文件解析逻辑

    # 静态文件夹 './static/dicom'
    dim_folder = os.path.join(app.static_folder, 'dicom')
    dim_filename = dicom_file.filename
    # 处理(修正)后的文件名
    fix_dim_filename = fix_filename(dim_filename)
    abs_fix_dim_file_path = os.path.join(dim_folder, fix_dim_filename)
    # 存储文件
    dicom_file.save(abs_fix_dim_file_path)
    # 处理文件
    dim_image_file_path = fix_dim_filename + '.png'
    abs_dim_image_file_path = os.path.join(dim_folder, dim_image_file_path)
    convert(abs_fix_dim_file_path, abs_dim_image_file_path)
    # 获取路径
    relative_image_path = os.path.join(app.static_url_path, 'dicom', dim_image_file_path)
    return jsonify({
        'code': 200,
        'msg': 'ok',
        'data': {
            'dicom': relative_image_path
        }
    })

def fix_filename(filename: str) -> str:
    """
    在文件名前添加 `20230626155935910277` + filename，防止出现重名被覆盖
    """
    datastr = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
    return f'{datastr}-{filename}'


if __name__ == '__main__':
    app.run(debug=True)
